package models

import (
	"encoding/json"
	"fmt"
	"net/url"
	//"time"

	"../global"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

func Init() {
	dbuser := global.Config["dbuser"]
	dbpassword := global.Config["dbpassword"]
	dbhost := global.Config["dbhost"]
	dbport := global.Config["dbport"]
	dbname := global.Config["dbname"]
	timezone := global.Config["timezone"]
	if dbport == "" {
		dbport = "3306"
	}
	dsn := dbuser + ":" + dbpassword + "@tcp(" + dbhost + ":" + dbport + ")/" + dbname + "?charset=utf8"
	if timezone != "" {
		dsn = dsn + "&loc=" + url.QueryEscape(timezone)
	}
	err := orm.RegisterDataBase("default", "mysql", dsn)
	if err != nil {
		panic("mysql connect error")
	}
	if global.Config["runmode"] == "dev" {
		orm.Debug = true
	}
	initLogger()
	ActInit()
}

func initLogger() {
	config := make(map[string]interface{})
	config["filename"] = global.Config["logpath"]
	config["level"] = logs.LevelDebug
	config["maxlines"] = 0
	config["maxsize"] = 0
	config["maxdays"] = 30
	config["rotate"] = true
	config["daily"] = true
	//config["separate"] = []string{"emergency", "alert", "critical", "error", "warning", "notice", "info", "debug"}    //需要单独写入文件的级别
	if global.Config["runmode"] == "dev" {
		//logs.EnableFuncCallDepth(true)  //是否开启异步
	} else {
		config["level"] = logs.LevelInfo
	}

	configStr, err := json.Marshal(config)
	if err != nil {
		fmt.Println("marshal failed,err:", err)
		return
	}
	logs.SetLogger(logs.AdapterFile, string(configStr))
	//logs.Debug("this is a test,my name is %s", "stu01")
	//logs.Trace("this is a trace,my name is %s", "stu02")
	//logs.Warn("this is a warn,my name is %s", "stu03")
}
